package one;

import java.util.*;

public class A003 {

    /**
     * 3.最长连续序列
     * @param args
     */
    public static void main(String[] args) {
        int[] nums = {9,1,4,7,3,-1,0,5,8,-1,6};
        longestConsecutive(nums);
    }


    /**
     * 解法二：利用set集合一直找到序列的最小值
     * @param nums
     * @return
     */
    public int longestConsecutive2(int[] nums) {
        Set<Integer> set = new HashSet<>();
        for(int x:nums) {
            set.add(x);
        }
        int ret=0;
        for(int x:set) {
            if(set.contains(x-1)) {
                continue;//一直找到连续序列的最小值
            }
            //找到了，一直往上找最大值
            int y = x+1;
            while(set.contains(y)) {
                y++;
            }
            ret = Math.max(ret,y-x);
        }
        return ret;
    }


    /**
     * 解法一：双指针
     * @param nums
     * @return
     */
    public static int longestConsecutive(int[] nums) {
        if(nums.length<=1) return nums.length;
        Arrays.sort(nums);
        int ret=0;
        for(int i=0;i<nums.length-1;i++) {
            int number = 1;
            int j=i+1;
            for(;j<nums.length;j++) {
                if(nums[j]-nums[j-1] == 1) {
                    //1.递减
                    number++;
                }else if(nums[j]-nums[j-1] == 0) {
                    //2.相等

                }else {
                    //3.非递增
                    break;
                }
            }
            //收集结果
            ret = Math.max(ret,number);
            i=j-1;
        }
        return ret;
    }
}
